package com.gz.purchase.app;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gz.purchase.R;
import com.gz.purchase.adapter.OutStorageCartAdapter;
import com.gz.purchase.adapter.SpinnerAdapter;
import com.gz.purchase.library.IAuthor;
import com.gz.purchase.library.IProduct;
import com.gz.purchase.library.listener.ConfirmOutStorageListener;
import com.gz.purchase.library.listener.GetOutStorageCartProductsListener;
import com.gz.purchase.library.listener.GetStorageRoomListener;
import com.gz.purchase.library.pojo.CustomerSpinnerObject;
import com.gz.purchase.library.pojo.StorageCheckProductInfo;
import com.gz.purchase.library.pojo.StorageRoomInfo;
import com.gz.purchase.library.pojo.UserInfo;
import com.gz.purchase.library.util.Constants;
import com.gz.purchase.library.util.CrashHandler;
import com.gz.purchase.library.util.PreferenceModel;
import com.gz.purchase.library.util.Tools;
import com.gz.purchase.util.ToastUtils;
import com.gz.purchase.widget.LoadingCover;
import com.gz.purchase.widget.SpinerPopWindow;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 出库车出库
 */
public class OutStorageCartActivity extends BaseActivity
        implements View.OnClickListener, LoadingCover.OnLoadingCoverRefreshListener,
        SpinerPopWindow.ISpinnerOnItemSelectListener,PullToRefreshBase.OnRefreshListener {

    private String TAG = OutStorageCartActivity.class.getSimpleName();
    private UserInfo info;
    private ImageView iv_actionbar_up;
    private TextView tv_actionbar_title;
    private TextView tv_actionbar_deliveryName;

    private RelativeLayout rl_choice_for_storeroom;
    private TextView tv_storeroom;//库房选择
    private TextView tv_add_to_outStorageCart;//确认出库
    private LoadingCover mLoadingCover;
    private Dialog mLoadingData;
    private PullToRefreshListView mPullListView;
    // 库房下拉相关变量
    private List<CustomerSpinnerObject> storageroomList ;
    private SpinnerAdapter partSpinnerAdapter;
    private SpinerPopWindow mPartSpinnerPopWindow;

    private OutStorageCartAdapter mAdapter;
    private List<StorageCheckProductInfo> mDataList;

    private MyGetOutStorageCartProductsListener myGetOutStorageCartProductsListener;
    private MyGetStorageRoomListener myGetStorageRoomListener;
    private MyConfirmOutStorageListener myConfirmOutStorage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_out_storage_cart);
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        mActionBar.setCustomView(R.layout.common_activity_head_layout);//自定义ActionBar布局
        initView();
        initListener();
        initData();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        myGetOutStorageCartProductsListener.release();
        myGetStorageRoomListener.release();
        myConfirmOutStorage.release();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_storeroom:
                if (storageroomList.size() == 0){ //如果库房列表为空，则从服务器获取
                    mLoadingData.show();
                    IProduct.getInstance().getStorageRoomList(myGetStorageRoomListener);
                }else{// 不为空就显示
                    mPartSpinnerPopWindow.setWidth(rl_choice_for_storeroom.getWidth());
                    mPartSpinnerPopWindow.showAsDropDown(rl_choice_for_storeroom);
                }
                break;
            case R.id.tv_add_to_outStorageCart:
                outStorageConfirm();
                break;
            case R.id.iv_actionbar_up:
                finish();
                break;
        }
    }

    /**
     * 确认出库
     * @return
     */
    public void outStorageConfirm(){
        StorageRoomInfo selectedStorageRoom= (StorageRoomInfo) tv_storeroom.getTag();
        Boolean isEmpty = false; // 用来记录是否存在商品的数量没填写或者为负数
        if (mDataList.size() <= 0){
            ToastUtils.showToast(this,"出库车为空");
            return ;
        }
        if (selectedStorageRoom == null){
            ToastUtils.showToast(this,"请选择目的库房");
            return ;
        }

        mLoadingData.show();
        JSONArray array = new JSONArray();
        try {
            for (int i = 0 ; i < mDataList.size() ; i ++){
                if (mDataList.get(i).getSelectNum() <= 0){// 如果有商品的数量没填写（默认0） 或者为负数，则跳出啊循环
                    isEmpty = true;
                    break;
                }
                StorageCheckProductInfo info  = mDataList.get(i);
                JSONObject object = new JSONObject();
                object.put("product_id",info.getProduct_id());
                object.put("product_num",info.getSelectNum());
                array.put(object);
            }

        } catch (JSONException e) {
            array = null;
            e.printStackTrace();
        }

        if (isEmpty){
            mLoadingData.dismiss();
            ToastUtils.showToast(this,"请正确填写商品数量");
            return;
        }

        if (array == null || array.length() <= 0){  // 异常的话
            mLoadingData.dismiss();
            ToastUtils.showToast(this, "操作异常，请重试");
            return;
        }
        CrashHandler.i(TAG,array.toString());
        IProduct.getInstance().outStorageConfirm(selectedStorageRoom.getStorage_id(), Tools.Base64Encode(array.toString()), myConfirmOutStorage);

    }
    @Override
    public void onLoadingCoverRefresh() {
        IProduct.getInstance().getStorageCartProducts(myGetOutStorageCartProductsListener);

    }
    // 点击库房列表触发以下方法
    @Override
    public void onSpinnerItemClick(int position) {
        StorageRoomInfo info = (StorageRoomInfo) storageroomList.get(position);
        tv_storeroom.setText(info.getStorage_name());
        tv_storeroom.setTag(info);
        for(int i = 0 ;i < storageroomList.size() ; i++){
            if (i == position){
                storageroomList.get(i).setIsSelected(true);
            }else{
                storageroomList.get(i).setIsSelected(false);
            }
        }
    }

    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        onLoadingCoverRefresh();

    }

    private void initView(){
        info = IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));
        iv_actionbar_up = (ImageView) this.findViewById(R.id.iv_actionbar_up);
        tv_actionbar_title = (TextView) this.findViewById(R.id.tv_actionbar_title);
        tv_actionbar_deliveryName = (TextView) this.findViewById(R.id.tv_actionbar_deliveryName);

        rl_choice_for_storeroom = (RelativeLayout) this.findViewById(R.id.rl_choice_for_storeroom);
        tv_storeroom = (TextView) this.findViewById(R.id.tv_storeroom);
        tv_add_to_outStorageCart = (TextView) this.findViewById(R.id.tv_add_to_outStorageCart);
        mLoadingCover = (LoadingCover) this.findViewById(R.id.layout_loading_cover);
        mPullListView = (PullToRefreshListView) this.findViewById(R.id.list);

        mLoadingData = new Dialog(this,R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);
    }

    private void initListener(){

        iv_actionbar_up.setOnClickListener(this);
        tv_storeroom.setOnClickListener(this);
        tv_add_to_outStorageCart.setOnClickListener(this);
        mLoadingCover.setOnLoadingCoverRefreshListener(this);

        myGetOutStorageCartProductsListener = new  MyGetOutStorageCartProductsListener(this);
        myGetStorageRoomListener = new MyGetStorageRoomListener(this);
        myConfirmOutStorage = new MyConfirmOutStorageListener(this);
        mPullListView.setOnRefreshListener(this);

    }

    private void initData(){
        tv_actionbar_title.setText("出库操作");
        if (info != null){
            tv_actionbar_deliveryName.setText(info.getName() + "：" + info.getUser_name());
        }

        mDataList = new ArrayList<StorageCheckProductInfo>();
        mAdapter = new OutStorageCartAdapter(this,mDataList);
        mPullListView.setAdapter(mAdapter);

        storageroomList = new ArrayList<CustomerSpinnerObject>();
        partSpinnerAdapter = new SpinnerAdapter(this,storageroomList);
        mPartSpinnerPopWindow = new SpinerPopWindow(this);
        mPartSpinnerPopWindow.setAdatper(partSpinnerAdapter);
        mPartSpinnerPopWindow.setItemListener(this);
        onLoadingCoverRefresh();
    }

    /**
     * 获取出库车商品的监听器
     */
    private static class MyGetOutStorageCartProductsListener extends GetOutStorageCartProductsListener {
        private OutStorageCartActivity mOuter;

        public MyGetOutStorageCartProductsListener(OutStorageCartActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<OutStorageCartActivity>(mOuter);
        }
        @Override
        public void onStorageCartIsEmpty() {
            mOuter.mLoadingCover.onRefreshFailed("出库车暂无数据");
            if (mOuter.mPullListView.isRefreshing()){
                mOuter.mPullListView.getLoadingLayoutProxy().refreshSuccess();
            }
            ToastUtils.showToast(mOuter, "出库车暂无数据");

        }

        @Override
        public void onResponseSuccess(List<StorageCheckProductInfo> storageCheckProductInfos) {
            if (storageCheckProductInfos == null){
                storageCheckProductInfos = new ArrayList<StorageCheckProductInfo>();
            }
            mOuter.mDataList.clear();
            mOuter.mDataList.addAll(storageCheckProductInfos);
            mOuter.mAdapter.notifyDataSetChanged();
            if ( mOuter.mPullListView.isRefreshing()) {
                mOuter.mPullListView.getLoadingLayoutProxy().refreshSuccess();
            }
            mOuter.mLoadingCover.onRefreshSuccess();

        }

        @Override
        public void onNoNetWork() {
            if (mOuter.mPullListView.isRefreshing()){
                mOuter.mPullListView.getLoadingLayoutProxy().refreshFailed();
            }
            mOuter.mLoadingCover.onRefreshFailed();
            ToastUtils.showToast(mOuter, Define.MSG_TOAST_NO_NETWORK);
        }

        @Override
        public void onResponseFailed() {
            if (mOuter.mPullListView.isRefreshing()){
                mOuter.mPullListView.getLoadingLayoutProxy().refreshFailed();
            }
            mOuter.mLoadingCover.onRefreshFailed();
            ToastUtils.showToast(mOuter,"获取出库车数据失败");
        }
    }

    /**
     * 获取库房列表的监听器
     */
    private static class MyGetStorageRoomListener extends GetStorageRoomListener {
        private OutStorageCartActivity mOuter;

        public MyGetStorageRoomListener(OutStorageCartActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<OutStorageCartActivity>(mOuter);
        }
        @Override
        public void onResponseSuccess(List<StorageRoomInfo> infos) {
            if (infos == null){
                onResponseFailed();
                return;
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            mOuter.storageroomList.clear();
            mOuter.storageroomList.addAll(infos);
            mOuter.mPartSpinnerPopWindow.setWidth(mOuter.rl_choice_for_storeroom.getWidth());
            mOuter.mPartSpinnerPopWindow.showAsDropDown(mOuter.rl_choice_for_storeroom);

        }

        @Override
        public void onNoStorageRoomInfo() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, "库房列表为空");
        }

        @Override
        public void onNoNetWork() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, Define.MSG_TOAST_NO_NETWORK);
        }

        @Override
        public void onResponseFailed() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, "获取库房列表失败");
        }
    }

    /**
     * 确认出库回到事件
     */
    private static class MyConfirmOutStorageListener extends ConfirmOutStorageListener {
        private OutStorageCartActivity mOuter;

        public MyConfirmOutStorageListener(OutStorageCartActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<OutStorageCartActivity>(mOuter);
        }

        @Override
        public void onResponseSuccess() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, "出库成功");
            mOuter.finish();
        }

        @Override
        public void onDataError(String msg) {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter,msg);
        }

        @Override
        public void onNoNetWork() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, Define.MSG_TOAST_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, "出库失败");

        }
    }

}
